package com.example.demo.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.example.demo.entity.EtUser;


public class SessionInterceptor implements HandlerInterceptor {


    private static String[] interceptUrl = new String[]{"/login.do","/addInformation.do","/delInfo","/addView","/listView","/userlistPage","getUserInfo"};

    
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
    	
    	boolean flag=true;

        String requestUrl = request.getRequestURI().replace(request.getContextPath(), "");
        /*
		int index=Arrays.binarySearch(allowUrl, requestUrl);
		System.err.println(index);
		*/
        if (null != interceptUrl && interceptUrl.length >= 1) {
            for (String url : interceptUrl) {
                if (requestUrl.contains(url)) {
                	flag=false;
                	break;
                }
            }
        }
        
        if(flag) {
        	return true;
        }

        EtUser user = (EtUser) request.getSession().getAttribute("etUser");
        System.err.println(String.valueOf(user));


        if (user != null&&user.getIsAdmin()==1) {
        	
            return true;  //结束后 继续调用postHandle(),  afterCompletion()  
        } else {
            //session中没用户则跳转到登录页面
            //传入当前链接，以跳转用
            response.sendRedirect("/home.htm");
            //request.getRequestDispatcher("/login/loginPage.do").forward(request, response);
            return false;
        }
        
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {
        // TODO Auto-generated method stub

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
        // TODO Auto-generated method stub

    }


}
